package com.ycsj.goldmedalnewconcept.parent.activity;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.ArithUtil;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.view.StarBar;
import com.ycsj.common.view.ZzHorizontalProgressBar;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.LpUtils;
import com.ycsj.goldmedalnewconcept.parent.adapter.EvaluateRvAdapter;
import com.ycsj.goldmedalnewconcept.parent.bean.EvaluateInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 评价老师
 * Created by Administrator on 2018/6/21 0021.
 */

public class ParentsEvaluateTeacherActivity extends BaseActivity implements View.OnClickListener, SrfManager.OnPullRefreshListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView ivEdit;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srf)
    SmartRefreshLayout srf;
    @BindView(R.id.rl_loading_view)
    RelativeLayout rlLoadingView;

    //老师ID
    private String teacherId;

    //界面刷新的标识
    public static final int EVALUATEUPDATE = 0x550;

    //数据集合
    private List<EvaluateInfo.ListBean> oldDatas;

    //适配器
    private EvaluateRvAdapter adapter;

    //头布局
    private View headView;

    //空视图
    private View emptyView;

    //评分控件
    private StarBar starBar;
    //进度条控件和显示进度的文字
    private ZzHorizontalProgressBar pbFive, pbFour, pbThree, pbTwo, pbOne;
    private TextView tvFive, tvFour, tvThree, tvTwo, tvOne, Score;

    //数据对象
    private EvaluateInfo info;

    @Override
    protected int getContentLayout() {
        return R.layout.parent_activity_evaluate_teacher;
    }

    @Override
    protected void init() {

        initStateBar();

        //初始化老师Id
        initTeacherId();

        //初始化视图
        initView();

        //初始化下拉刷新控件
        initSrf();

        //设置数据
        initRv();

        //请求数据
        http(BqaManager.NORML);
    }


    /**
     * 初始化老师ID
     */
    private void initTeacherId() {
        //校长端需要先选择老师,然后携带给该页面,老师端teacherId就是自己的账号,家长端登录时候保存
        if ("3".equals(AccountUtils.getRole(this))) {
            teacherId = getIntent().getStringExtra("teacherid");
        } else if ("2".equals(AccountUtils.getRole(this))) {
            teacherId = AccountUtils.getAccount(this);
        } else if ("1".equals(AccountUtils.getRole(this))) {
            teacherId = AccountUtils.getTeacher(this);
        }
    }


    /**
     * 初始化视图
     */
    public void initView() {

        String role = AccountUtils.getRole(this);

        if ("2".equals(role) || "3".equals(role)) {
            //设置标题
            tvTitle.setText("评价记录");
        } else {
            tvTitle.setText("评价老师");
        }

        if ("1".equals(role)) {
            //只有家长端时才显示评价老师的按钮
            RelativeLayout.LayoutParams lp = LpUtils.getRelatLp(92, 66);
            lp.addRule(RelativeLayout.CENTER_IN_PARENT);
            ivEdit.setLayoutParams(lp);
            ivEdit.setImageResource(R.drawable.parent_edit);
            ivEdit.setVisibility(View.VISIBLE);
        } else {
            ivEdit.setVisibility(View.GONE);
        }

        headView = View.inflate(this, R.layout.parent_headview_evaluate, null);
        starBar = headView.findViewById(R.id.starbar);
        starBar.setEnabled(false);
        pbOne = headView.findViewById(R.id.pb_one);
        pbTwo = headView.findViewById(R.id.pb_two);
        pbThree = headView.findViewById(R.id.pb_three);
        pbFour = headView.findViewById(R.id.pb_four);
        pbFive = headView.findViewById(R.id.pb_five);
        tvOne = headView.findViewById(R.id.tv_one);
        tvTwo = headView.findViewById(R.id.tv_two);
        tvThree = headView.findViewById(R.id.tv_three);
        tvFour = headView.findViewById(R.id.tv_four);
        tvFive = headView.findViewById(R.id.tv_five);
        Score = headView.findViewById(R.id.tv_show_score);
    }


    /**
     * 初始化下拉刷新
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, this);
    }

    /**
     * 请求服务器数据的方法
     *
     * @param method
     */
    private void http(final int method) {
        Map<String, String> map = new HashMap<>();

        map.put("c", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        if ("1".equals(AccountUtils.getRole(this))) {
            //家长获取对老师的评价
            map.put("type", "10");
        } else {
            //老师或校长获取对老师的评价
            map.put("type", "11");
        }
        map.put("teachermobile", teacherId);

        LogUtils.iTag("test", HttpAddress.EVALUATERECORD + "&type=10&c="
                + AccountUtils.getAccount(this) + "&role=" + AccountUtils.getRole(this)
                + "&teachermobile=" + teacherId);

        HttpUtils.post(HttpAddress.EVALUATERECORD, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoadingView, srf, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {

                if (rlLoadingView != null && rlLoadingView.getVisibility() == View.VISIBLE) {
                    rlLoadingView.setVisibility(View.GONE);
                }

                if (!TextUtils.isEmpty(response)) {
                    try {
                        info = GsonUtil.jsonToBean(response, EvaluateInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("1".equals(info.state)) {

                            //获取到数据后初始化头部数据
                            initHeadViewData(info);

                            List<EvaluateInfo.ListBean> newDatas = info.list;

                            //倒序处理
//                            Collections.reverse(newDatas);

                            if (method == BqaManager.NORML) {

                                oldDatas.clear();
                                oldDatas.addAll(newDatas);
                                BqaManager.setRv(emptyView, ParentsEvaluateTeacherActivity.this,
                                        adapter, rv, null);
                            } else {
                                oldDatas.clear();

                                //更新数据
                                BqaManager.updateRvBySmf(method, srf, rv, oldDatas, newDatas, adapter);
                            }

                        } else if ("10043".equals(info.state)) {
                            ToastUtils.showShort("账号无对应的教师信息");
                            BqaManager.setRv(emptyView, ParentsEvaluateTeacherActivity.this,
                                    adapter, rv, null);
                            //空数据头部数据
                            initHeadViewEmptyData();

                        } else {
                            Log.i("test", "错误,状态码是:" + info.state);

                            //空数据头部数据
                            initHeadViewEmptyData();
                            if (method == BqaManager.NORML) {
                                BqaManager.setRv(emptyView, ParentsEvaluateTeacherActivity.this,
                                        adapter, rv, null);
                            } else {
                                //下拉刷新,停止下拉刷新
                                srf.finishRefresh();
                            }
                        }
                    } else {
                        Log.i("test", "返回数据为空");
                    }
                } else {
                    Log.i("test", "返回数据为空");
                }
            }
        });
    }


    /**
     * 设置列表
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view_top, null);
        TextView tvMessage = emptyView.findViewById(R.id.tv_content);
        tvMessage.setText("暂无评价记录");
        adapter = new EvaluateRvAdapter(this, R.layout.parent_rv_evaluate_teacher, oldDatas);
        adapter.addHeaderView(headView);
    }


    /**
     * 初始化头部数据
     */
    private void initHeadViewData(EvaluateInfo info) {

        List<EvaluateInfo.PointBean> point = info.point;

        if (point != null && point.size() != 0) {
            EvaluateInfo.PointBean pointBean = point.get(0);

            double div = ArithUtil.div(pointBean.SUM_SCORE, pointBean.COUNT, 2);

            //设置评分控件的值
            starBar.setStarMark(Float.parseFloat(div + ""));

            //设置评分值
            Score.setText(div + "");

        } else {
            //没数据设置空
            //设置评分控件的值
            starBar.setStarMark(5.00f);

            //设置评分值
            Score.setText("5.00");
        }


        //设置默认进度值
        pbFive.setProgress(100);
        pbFour.setProgress(0);
        pbThree.setProgress(0);
        pbTwo.setProgress(0);
        pbOne.setProgress(0);

        tvFive.setText("100.00%");
        tvFour.setText("0.00%");
        tvThree.setText("0.00%");
        tvTwo.setText("0.00%");
        tvOne.setText("0.00%");


        //设置进度条的值
        List<EvaluateInfo.DataBean> data = info.data;
        if (data == null || data.size() == 0) {
            //表示没有评价,默认全为0
            initHeadViewEmptyData();
        } else {
            //表示有评价
            for (int i = 0; i < data.size(); i++) {
                EvaluateInfo.DataBean dataBean = data.get(i);
                setPbState(dataBean);
            }
        }


        //set padding
        pbFive.setPadding(0);
        pbFour.setPadding(0);
        pbThree.setPadding(0);
        pbTwo.setPadding(0);
        pbOne.setPadding(0);

        //set bacground color
        pbFive.setBgColor(getResources().getColor(R.color.parent_pb_bg));
        pbFour.setBgColor(getResources().getColor(R.color.parent_pb_bg));
        pbThree.setBgColor(getResources().getColor(R.color.parent_pb_bg));
        pbTwo.setBgColor(getResources().getColor(R.color.parent_pb_bg));
        pbOne.setBgColor(getResources().getColor(R.color.parent_pb_bg));

        //set progress color
        pbFive.setProgressColor(getResources().getColor(R.color.parent_pb_progress));
        pbFour.setProgressColor(getResources().getColor(R.color.parent_pb_progress));
        pbThree.setProgressColor(getResources().getColor(R.color.parent_pb_progress));
        pbTwo.setProgressColor(getResources().getColor(R.color.parent_pb_progress));
        pbOne.setProgressColor(getResources().getColor(R.color.parent_pb_progress));

    }

    /**
     * 根据服务器返回的分级等级进行评分
     *
     * @param info
     */
    private void setPbState(EvaluateInfo.DataBean info) {
        //计算进度
        int progress = ArithUtil.bs(info.COUNT, info.SUM);

        double div = ArithUtil.div(info.COUNT, info.SUM, 4);
        String showPb = Float.parseFloat(div * 100 + "") + "";
        if (1 == info.SCORE) {
            //1星
            pbOne.setProgress(progress);
            tvOne.setText(showPb + "%");
        } else if (2 == info.SCORE) {
            //2星
            pbTwo.setProgress(progress);
            tvTwo.setText(showPb + "%");
        } else if (3 == info.SCORE) {
            //3星
            pbThree.setProgress(progress);
            tvThree.setText(showPb + "%");

        } else if (4 == info.SCORE) {
            //4星
            pbFour.setProgress(progress);
            tvFour.setText(showPb + "%");

        } else if (5 == info.SCORE) {
            //5星
            pbFive.setProgress(progress);
            tvFive.setText(showPb + "%");
        }
    }

    /**
     * 当没有1到5星的数据返回时设置5个进度条的默认值
     */
    private void initHeadViewEmptyData() {

        //设置评分控件的值
        starBar.setStarMark((float) 5.00);

        //设置评分值
        Score.setText("5.00");

        //设置几个进度条的值
        //set progress value
        pbFive.setProgress(100);
        pbFour.setProgress(0);
        pbThree.setProgress(0);
        pbTwo.setProgress(0);
        pbOne.setProgress(0);

        tvFive.setText("100.00%");
        tvFour.setText("0.00%");
        tvThree.setText("0.00%");
        tvTwo.setText("0.00%");
        tvOne.setText("0.00%");

        //set padding
        pbFive.setPadding(0);
        pbFour.setPadding(0);
        pbThree.setPadding(0);
        pbTwo.setPadding(0);
        pbOne.setPadding(0);

        //set bacground color
        pbFive.setBgColor(getResources().getColor(R.color.parent_pb_bg));
        pbFour.setBgColor(getResources().getColor(R.color.parent_pb_bg));
        pbThree.setBgColor(getResources().getColor(R.color.parent_pb_bg));
        pbTwo.setBgColor(getResources().getColor(R.color.parent_pb_bg));
        pbOne.setBgColor(getResources().getColor(R.color.parent_pb_bg));

        //set progress color
        pbFive.setProgressColor(getResources().getColor(R.color.parent_pb_progress));
        pbFour.setProgressColor(getResources().getColor(R.color.parent_pb_progress));
        pbThree.setProgressColor(getResources().getColor(R.color.parent_pb_progress));
        pbTwo.setProgressColor(getResources().getColor(R.color.parent_pb_progress));
        pbOne.setProgressColor(getResources().getColor(R.color.parent_pb_progress));

    }

    /**
     * 下拉刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        http(BqaManager.PULLREFRESH);
    }

    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back, R.id.lv_edit})
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.lv_edit) {
            //添加评价
            if (null != info) {
                ParentsAddNewEvaluateActiivty.goActivity(this, AccountUtils.getClassNum(this), AccountUtils.getTeacher(this),
                        info.name, info.sex, info.icon);
            } else {
                ToastUtils.showShort("未获取到数据");
            }
        }
    }


    /**
     * 事件
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        //更新界面的消息
        if (null != busInfo && busInfo.type == EVALUATEUPDATE) {
            http(BqaManager.PULLREFRESH);
        }
    }

}
